<!-- 在表单中使用popover效果展示文件上传控件 -->
<template>
  <el-popover
    placement="top"
    width="480"
    trigger="hover"
    @show="handleShow">
    <el-upload
      :before-remove="beforeRemove"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handelError"
      :file-list="fileList"
      list-type="picture-card"
      v-bind="fld"
      :action="fld.action"
      size="mini"
      ref="elupload">
      <el-button type="primary" ref="btnUpload">{{fld.title}}</el-button>
    </el-upload>
    <!-- 预览 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-button slot="reference" size="mini" @click="handleClick">{{textButton}}</el-button>
  </el-popover>
</template>
<script>
define(['vue'],function(vue){
  return vue.component('comp-image-popover',{
    template: template,
    props:['fld','value'],
    data:function(){      
      return {
        fileList: this.value || [],        
        // fileList: [
        //   {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
        //   // {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
        // ],
        dialogImageUrl: '',
        dialogVisible: false,
        action:this.fld.action,
        actionRemove : this.fld.actionRemove,
        // textBtn : "点击上传" + (this.value?`(${this.value.length})`:''),
        textBtn : "点击上传",
      };
    },    
    computed:{
      textButton : function() {
        // if(this.$refs.elupload) {
        //   var len = this.$refs.elupload.uploadFiles.length;
        //   if(len>0) {
        //      return `${this.textBtn}(${len})`;
        //   } else {
        //     return this.textBtn
        //   }
        // }
        //初始化时，不存在 this.$refs.elupload
        return this.textBtn + (this.value?`(${this.value.length})`:'')
      },
      //上下移动时会触发这个变化
      // fileList: function(){
      //   return this.value || [];
      // }, 
    },
    // watch : {
    //   //在选中不同子表记录时会触发这个变化
    //   'value':  {
    //     handler : function(newVal,oldVal) {
    //       // debugger;
    //       dump(this.fld.name+' image value changed',oldVal,newVal);
    //       // dump(`弹出选择控件${this.fld.name}.displayText change`,newVal,oldVal);        
    //       // this.text = newVal;
    //     }
    //   }
    // },
    methods:{
      test : function(){
        dump('test');
      },
      //点击按钮开始选择文件
      handleClick : function(){
        this.$refs.elupload.$refs['upload-inner'].$refs.input.click();
        // this.popoverVisible = !this.popoverVisible;
        // //如果没有图片，自动选择文件
        // var files = this.$refs.elupload.uploadFiles;
        // if(files.length==0 && this.popoverVisible) {
        //   //模拟点击上传按钮
        //   this.$refs.elupload.$refs['upload-inner'].$refs.input.click();
        // }
      },
      setFileList : function(fl) {
        this.fileList = fl==''?[]:fl;
      },
      'beforeRemove' : function(file, fileList){
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      //点击文件列表项时触发
      'handlePreview' : function(file){
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      'handelError': function(err, file, fileList) {
        this.$notify.warning('图片保存失败');
        console.error(err);
        return false;
      },
      'handleRemove' : function(file, fileList){
        //从服务器删除图片
        if(this.actionRemove) {
          var param = {url:file.url};
          this.$http.post(this.actionRemove,param).then((res)=>{
            if(!res.data.success) {
              this.$notify.error({
                'title':'服务器删除图片失败',
                'message':'response.data.success not found'
              });
              dump(res);
              return false;
            }
            // this.fileList = fileList;
            this.$emit('input',fileList);
            // this.$emit('changeimg',fileList,this);
            // this.$notify.success({
            //   title:'图片删除成功',
            //   message:res.data.msg,
            // });
            //删除回调
            var key = `${this.fld.name}:remove`;
            if(!this.$root.callbacks[key]) return;
            this.$root.callbacks[key].apply(this,arguments);
          }).catch(function (error) {
            dump(error);
            this.$notify.error({
              'title':'请求失败',
              'message':'请求失败,检查url或者其他设置'
            });
          });
        } else {
          console.warn('未发现 actionRemove 属性');
          //如果没有设置服务器删除代码,直接删除回调
          var key = `${this.fld.name}:remove`;
          if(!this.$root.callbacks[key]) return;
          this.$root.callbacks[key].apply(this,arguments);
        }
      },
      'handleExceed' : function(files, fileList){
        this.$message(`当前限制选择${this.fld.limit}个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      'handleSuccess':function(response, file, fileList) {
        if(!response.success) {
          this.$notify.warning('图片保存存在问题,您需要重新上传!');
          return false;
        }

        if(!response.imgPath) {
          this.$notify.warning('图片保存后未返回imgPath!');
          return false;
        }
        file.url=response.imgPath;
        var files = this.$refs.elupload.uploadFiles;
        //格式化fileList,去掉不需要的字段信息
        var fl = [];
        files.forEach((item,i)=>{
          // dump(item);
          var imageId = item.imageId ? item.imageId : (item.response ? item.response.imageId : null);
          fl.push({name:item.name,url:item.url,imageId:imageId});
        });
        this.$emit('input',fl);
        // dump(fileList,this.fileList);
        // this.$emit('changeimg',fileList,this);

        //文件上传成功后回调
        var key = `${this.fld.name}:success`;
        if(!this.$root.callbacks[key]) return;
        this.$root.callbacks[key].apply(this,arguments);
      },
      //显示时,根据value值改变fileList,
      //本来可以使用compputed简化代码,但是会导致上传后闪烁的问题
      //所以延迟到显示时同步filelist
      //一个具有代表性的场景时:上传后->上下移动->再次打开
      handleShow : function() {
        // this.fileList = this.value || [];
      },
    },
    mounted: function(){
      if(this.fld.action=='') {
        console.warn(`文件上传控件${this.fld.name}未定义action`);
        return ;
      }
      // this.$refs.btnUpload.click();
      // dump('file mounted:this:',this);
    }

  });  
});
</script>